package com.newcoder.community.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class CommunityUtil {

    // 生成随机字符串
    public static String generateUUID(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }

    // MD5加密
    // hello -> abc123def456
    // hello + 3e4a8(随机) -> abc123def456abc222
    public static String md5(String key){
        //用导入的apache工具包判空
        if(StringUtils.isBlank(key)){
            return null;
        }
            //spring自带工具加密
            return DigestUtils.md5DigestAsHex(key.getBytes());
    }

    // 得到JSON格式字符串
    public static String getJSONString(int code, String msg, Map<String, Object> map) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("msg", msg);
        if (map != null) {
            for (String key : map.keySet()) {
                jsonObject.put(key, map.get(key));
            }
        }
        return jsonObject.toJSONString();
    }

    public static String getJSONString(int code, String msg) {
        return getJSONString(code, msg, null);
    }

    public static String getJSONString(int code) {
        return getJSONString(code, null, null);
    }

//    public static void main(String[] args) {
//        Map<String ,Object> map = new HashMap<>();
//        map.put("name", "龙宝");
//        map.put("age", 80);
//        System.out.println(getJSONString(88, "sb", map));
//    }

}
